<?php

/**
 * 后台访问IP限制管理
 * File Name：Security_ipController.php
 * File Encoding：UTF-8
 * File New Time：2014-5-27 10:25:34
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class Security_ipController extends AdminBase {

    public function actionIndex() {
        //搜索
        if (IS_POST) {
            $this->redirect(self::U(Yii::app()->getController()->getAction()->id, $_POST));
            exit;
        }
        $model = AllowIp::model();
        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        //分页数
        $limit = 20;
        //条件数组
        $where = array(
            'order' => 'status desc,id desc',
        );
        $status = (int) $_GET['status'];
        if ($status) {
            if ($status == 1) {
                $where['status'] = 1;
            } else if ($status == 2) {
                $where['status'] = 0;
            }
            $this->assign('status', $status);
        }
        $keyword = trim($_GET['keyword']);
        if ($keyword) {
            $where['ip'] = array('LIKE', "%{$keyword}%");
            $this->assign('keyword', $keyword);
        }

        $criteria = $model->where($where);
        //信息总数
        $count = $model->count($criteria);
        //分页
        $page = self::page($count, $limit, $pageId);
        //查询信息
        $criteria->limit = $page->listRows;
        $criteria->offset = $page->firstRow;
        $data = $model->findAll($criteria);

        $this->assign("Page", $page->show());
        $this->assign('data', $data);
        $this->assign('count', $count);
        $this->render();
    }

    public function actionDelete() {
        $id = Yii::app()->request->getParam('id');
        $data = AllowIp::model()->findByPk($id);
        if (empty($data)) {
            $this->error('该信息不存在！');
        }
        if ($data->status) {
            $data->status = 0;
        } else {
            $data->status = 1;
        }
        if ($data->save(false)) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function actionAdd() {
        if (IS_POST) {
            $ip = $_POST['ip'];
            if (empty($ip)) {
                $this->error('IP地址不能为空！');
            }
            if (AllowIp::model()->addIp($ip)) {
                $this->success('添加成功！', self::U('index'));
            } else {
                $error = AllowIp::model()->getOneError();
                $this->error($error ? $error : '添加失败！');
            }
        } else {
            $this->render();
        }
    }

}
